package com.hmall.search.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.common.constants.ElasticConstants;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.domain.dto.ItemSearchMqDTO;
import com.hmall.common.utils.BeanUtils;

import com.hmall.search.domain.po.ItemDoc;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;


@Slf4j
@RequiredArgsConstructor
@Component
public class ElasticSearchListener {
    private final RestHighLevelClient client;
    private final ItemClient itemClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.ITEMS_QUEUE),
            exchange = @Exchange(name = MqConstants.ITEMS_EXCHANGE),
            key = MqConstants.ITEMS_KEY
    ))
    public void listenItemDoc(ItemSearchMqDTO itemSearchMqDTO) {
        switch (itemSearchMqDTO.getMqSearchEnum()){
            case ITEM_INSERT_OR_UPDATE:
                itemsInsertOrUpdateDocument(itemSearchMqDTO.getItemId());
                break;
            case ITEM_DELETE:
                itemsDeleteDocument(itemSearchMqDTO.getItemId());
                break;
            default:
                log.info("未知操作");
                break;
        }
    }
    private void itemsDeleteDocument(Long itemId){
        // 1.准备request,两个参数一个是索引库名，第二个是文档id
        DeleteRequest deleteRequest = new DeleteRequest(ElasticConstants.ITEM_INDEX_NAME,itemId.toString());
        try {
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("移除索引库中的商品出错了:{}", e.getMessage());
        }
    }

    private void itemsInsertOrUpdateDocument(Long itemId){
        // 根据id查询商品信息
        ItemDTO itemDTO = itemClient.queryItemById(itemId);
        // 1.转换为文档类型
        ItemDoc itemDoc = BeanUtils.toBean(itemDTO, ItemDoc.class);
        // 设置更新时间 运维itemDTO中没有这个属性
        itemDoc.setUpdateTime(LocalDateTime.now());
        // 2.将itemDoc转换为json
        String doc = JSONUtil.toJsonStr(itemDoc);
        // 3.准备request
        IndexRequest indexRequest = new IndexRequest(ElasticConstants.ITEM_INDEX_NAME).id(itemDoc.getId());
        // 4.准备json文档
        indexRequest.source(doc, XContentType.JSON);
        // 5.发送请求
        try {
            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.info("添加索引库的商品出错了:{}", e.getMessage());
        }
    }

}
